package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    //根据id和status=1，获取获取菜品数据
    @GetMapping("/dish/list")
    private ResultInfo findList(long categoryId,
                                @RequestParam(defaultValue = "1") Integer status) {
        //1. 从Redis根据categoryId获取值
        String key = "dish_" + categoryId;
        List<Dish> dishList = (List<Dish>) redisTemplate.opsForValue().get(key);

        //2. 判断是否为NULL
        if (CollectionUtil.isNotEmpty(dishList)){
            log.info("在Redis中获取到的");
            //2.1 不为空就直接在Redis中获取值
            return ResultInfo.success(dishList);

        }else {
            log.info("在数据库中获取到的");
            //2.2 为空的话在数据库里查询，查询后放入Redis中
            dishList = dishService.findList(categoryId, status);
            redisTemplate.opsForValue().set(key,dishList);
            return ResultInfo.success(dishList);

        }
    }


}
